<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DB;
use App\Components\Tools;
use App\Components\DyToools;
use App\Models\DyModels\Douyin;
use App\Models\DyModels\HandleVideo;

/**
 * 获取企业号意向客户（企业号独有）
 */
class DyEnterprise extends Command {

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'DyEnterprise';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '获取企业号意向客户（企业号独有）';
    private $url = '';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle() {
        Tools::commandsLog('DyEnterprise:' . date("Y-m-d H:i:s"));
        $this->url = Tools::getOneconfig("/config/third.json", array('douyin', 'dy_url'));
        $this->getEnterprise();
    }

    //获取意向客户----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    function getEnterprise() {
        set_time_limit(0);
        $userTokenListTrue = new HandleVideo();
        $userTokenListTrue = $userTokenListTrue->userqyhTokenListTrue();
        //print_r($userTokenListTrue);exit();
        if ($userTokenListTrue) {
            foreach ($userTokenListTrue as $k => $v) {
                // if($k==0){
                $this->getEnterpriseData($v['open_id'], 1);
                // }
            }
        }
    }

    //  获取意向客户的方法
    function getEnterpriseData($open_id, $cursor) {//
        $userToken = new HandleVideo();
        $infoToken = new Douyin();
        $DyToools = new DyToools();
        $token = $userToken->userToken($open_id);
        $start_time = strtotime("-1 year -0 month -0 day"); //int类型 时间戳吧 设定一年内有互动的都获取
        $end_time = time(); //int类型 结束时间
        $url = $this->url . "/enterprise/leads/user/list/?open_id={$token['open_id']}&access_token={$token['access_token']}&cursor={$cursor}&count=20";
        $url.="&start_time=$start_time&end_time=$end_time&action_type=0";
        $data = $this->getJson($url);
        //echo '<pre/>'; print_r($data);
        if (isset($data['data']['error_code']) && $data['data']['error_code'] == 0) {
            if (isset($data['data']['users']) && $data['data']['users']) {
                //更新、添加用户意向客户
                $userToken->upDyUserEnterprise($data['data']['users'], $open_id);
            }
            if ($data['data']['cursor'] > 0 && $data['data']['has_more']) {
                $this->getEnterpriseData($open_id, $data['data']['cursor']);
            }
        } elseif (isset($data['data']['error_code']) && $data['data']['error_code'] == 10008 || $data['data']['error_code'] = 2190008) {

            // access_token 过期
            $dataOne = $DyToools->refresh_token($token['refresh_token']);
            if (isset($dataOne['data']['error_code']) && $dataOne['data']['error_code'] == 0) {
                $infoToken->upToken($dataOne['data'], $open_id); //更新Token
                $this->getEnterpriseData($open_id, $cursor);
            } elseif (isset($dataOne['data']['error_code']) && $dataOne['data']['error_code'] == 10010) {


                //refresh_token 过期
                $dataTwo = $DyToools->renew_refresh_token($token['refresh_token']);
                if (isset($dataTwo['data']['error_code']) && $dataTwo['data']['error_code'] == 0) {


                    $infoToken->upRef($dataTwo['data'], $open_id); //更新refresh_token
                    $this->getEnterpriseData($open_id, $cursor);
                } else {
                    $infoToken->upTokenStatus($open_id); //授权过期需用户重新授权 更改授权状态 为 0
                }
            }
        }
    }

    //get请求
    function getJson($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60); //连接后等待时间
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); //连接前等待时间
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //为true，则会跟踪爬取重定向页面，否则，不会跟踪重定向页面
        curl_setopt($ch, CURLOPT_ENCODING, ""); //返回乱码处理
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }

}
